import React, { Component } from "react";

import { BrowserRouter as Router, Route, Link, Redirect, Switch } from "react-router-dom";
import {
    Layout, Menu, Icon, Table, Divider, Button, Modal, Form, Input, DatePicker,
    Select, Popconfirm, message, Alert, TreeSelect, TimePicker, Tree,
    AutoComplete, Tabs, Col, Row, Dropdown, Card, Pagination, Spin, Skeleton,
    Drawer, Tag, Badge, Radio, Steps, Transfer, notification, Empty, Calendar, Checkbox, Upload, List, Avatar
} from "antd";




import { addGridOneApi, addGridTwoApi, addGridThreeApi, addGridStudentApi, addGridMemberApi, addGridFiveOldStaffApi, addGridOutAdminApi, getAllInGridMemberTypeApi, getAllGridChargeLevelApi, addGridChargeInfoApi, addGridAddressInfoApi, addGridAddressAndChargeInfo, getTotalGridInfoApi, addGridMember1Api, deleteAllGridInfoApi, deleteTotalGridInfoApi } from "../js/inadmingridApi.js"


import {
    inAdminGridApi, getAllInAdminGridMemberByGridparentApi, updateInAdminGridApi, deleteInAdminGridApi,
    getAllGridByGridparentIdApi, updateGridInfoApi, deleteGridInfoApi, isHasGridInfoApi, getFirstGridAddressInfoApi,
    getFirstGridChargeInfoApi, addFirstGridInfoApi, getEchartsGridByGridparentIdApi
} from "../js/inadmingridApi.js"

import { basrUrl } from '../js/config.js'

import { gridInAdminUrl } from "../js/config.js"
import * as echarts from 'echarts'


const { Step } = Steps;
const TabPane = Tabs.TabPane;
const FormItem = Form.Item;
const Option = Select.Option;

const gridGrade = ['总网格长', '一级网格长', '二级网格长', '三级网格长', '网格员']


const success = () => {
    message.success({
        content: '操作成功',
        className: 'custom-class',
        style: {
            marginTop: '48vh',
        },
    });
};
const fail = (s) => {
    message.error({
        content: s,
        className: 'custom-class',
        style: {
            marginTop: '48vh',
        },
    });
};




//导入校内网格长信息
class ImportGridOneData extends Component {

    constructor(props) {
        console.log("import==========================")
        super(props);
        this.state = {
            fileList: [],
            uploading: false,
            addVisible: false,
            buttonFlag: '',
            tableLoading: false,
            columnsData: [],
            filteredInfo: null,
            sortedInfo: null,
            allGridGrade: [],
            modlVisible: false,
            modAddlVisible: false,
            modlVisible2: false,
            modlVisible3:false,
            selectrecord: {},
            // gridMember: [],
            isHasGridInfo: false,
            gridInfo: [],
            totalInfo:[],
            chartData: [],
            chartLoading: true,
            totalName:"",
            totalPhone:""
        }

        this.refreshData = this.refreshData.bind(this);
    }

    componentDidMount() {
        this.refreshData();
    }


    handleChange = (pagination, filters, sorter) => {
        this.setState({
            filteredInfo: filters,
            sortedInfo: sorter,
        });
    };

    clearFilters = () => {
        this.setState({ filteredInfo: null });
    };

    clearAll = () => {
        this.setState({
            filteredInfo: null,
            sortedInfo: null,
        });
    };


    showAddModal = (e) => {
        this.setState({
            addVisible: true,
            fileList: [],
            buttonFlag: e
        });
    }

    handleCancel = e => {
        this.setState({
            addVisible: false,
            fileList: [],
            uploading: false
        });
    };

    handleUpload = (e) => {
        let schoolId = sessionStorage.getItem("departmentId")
        const { fileList, buttonFlag } = this.state;
        const formData = new FormData();
        fileList.forEach(file => {
            formData.append('upfile', file);
        });
            //.log("zsybiaoge", formData);

        this.setState({
            uploading: true,
        });

        formData.append('schoolId', schoolId)

        if (buttonFlag == 1) {
           
            addGridMemberApi(formData).then((res) => {
                if (res.data.status == '1') {
                    this.setState({
                        fileList: [],
                        uploading: false,
                    });
                    this.refreshData();
                    message.success(res.data.success);
                }
                else if(res.data.status == '0'){
                    this.setState({
                        uploading: false,
                    });
                    message.error("第"+res.data.error+"行存在空格、换行符等非法字符，请清除表格内容格式！");
                }else{
                    this.setState({
                        uploading: false,
                    });
                    message.error(res.data.rpeat, 10);
                }
                this.setState({
                    fileList: [],
                    uploading: false,
                });
            })
                .catch((e) => {
                    if (e.response) {
                        //请求已发出，服务器返回状态码不是2xx。
                        console.info(e.response.data)
                        console.info(e.response.status)
                        console.info(e.response.headers)
                    } else if (e.request) {
                        // 请求已发出，但没有收到响应
                        // e.request 在浏览器里是一个XMLHttpRequest实例，
                        // 在node中是一个http.ClientRequest实例
                        console.info(e.request)
                    } else {
                        //发送请求时异常，捕捉到错误
                        console.info('error', e.message);
                    }
                    console.info(e.config)
                })
                

        }

        else {
            return;
        }


    }

    handleClickOpenModal = (type, record) => {
        console.log(record)
        if (type == 'update') {
            console.log("update")
            this.setState({
                modlVisible: true,
                selectrecord: record,
            })
        } else if (type == 'add') {
            this.setState({
                modAddlVisible: true,
                selectrecord: record,
            })
        }

    }
    handleClickOpenModal2 = () => {
        this.setState({
            modlVisible2: true,
        })
    }
    confirmDelete1=()=>{
           
            deleteAllGridInfoApi(sessionStorage.getItem("departmentId"))
            .then(res=>{
                if(res.data=='success'){
                    this.refreshData()
                    success()
                  //  console.log("已经删除")
                }
                else {
                    fail('删除失败')
                }
            }).catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message);
                }
                console.info(e.config)
            });
    }
    handleClickOpenModal3=() =>{
        this.setState({
            modlVisible3:true,
        })
    }

    confirmDelete = (record) => {
        const schoolId = parseInt(sessionStorage.getItem("departmentId"))
        deleteGridInfoApi(record.id || record.key, schoolId)
            .then(res => {
                if (res.data == 'success') {
                    this.refreshData()
                    success()
                }
                else {
                    fail('删除失败')
                }
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message);
                }
                console.info(e.config)
            });
    }
    confirmDeleteTotal = (record) => {
        const schoolId = parseInt(sessionStorage.getItem("departmentId"))
        deleteTotalGridInfoApi(record.id || record.key, schoolId)
            .then(res => {
                if (res.data == 'success') {
                    this.refreshData()
                    success()
                }
                else {
                    fail('删除失败')
                }
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message);
                }
                console.info(e.config)
            });
    }

    refreshData() {
        this.setState({
            tableLoading: true
        });
        getAllGridByGridparentIdApi(parseInt(sessionStorage.getItem("departmentId")), 0)
            .then((res) => {
                this.setState({
                    gridInfo: res.data,
                    tableLoading: false
                })
            })
        getTotalGridInfoApi(sessionStorage.getItem("departmentId"))
           .then((res)=>{
            if(res.data.length>0){
                this.setState({
                    totalName:res.data[0].gridcharge,
                    totalPhone:res.data[0].phone,
                })
            }else{
                this.setState({
                    totalName:'',
                    totalPhone:''
                })
            }
            this.setState({
                totalInfo:res.data,
                tableLoading:false
            })
            
        })

        isHasGridInfoApi(parseInt(sessionStorage.getItem("departmentId")))
            .then((res) => {
                console.log(res.data)
                if (res.data == "success") {
                    this.setState({
                        isHasGridInfo: false
                    })
                } else {
                    this.setState({
                        isHasGridInfo: true
                    })
                }
            })
    }

    setModalVisible(modlVisible) {
        this.setState({
            modlVisible: modlVisible,
            selectrecord: {}
        })
    }
    setModalVisible2(modlVisible) {
        this.setState({
            modlVisible2: modlVisible,
        })
    }
    setModalVisible3(modlVisible) {
        this.setState({
            modAddlVisible: modlVisible,
        })
    }
    setModalVisible4(modlVisible){
        this.setState({
            modlVisible3:modlVisible,
        })
    }

    onRef = (ref) => {
        this.child = ref
    }

    callback = (key) => {
        this.setState({
            chartLoading: true
        })
        if(key == 2){
            //获取echarts数据集
            getEchartsGridByGridparentIdApi(parseInt(sessionStorage.getItem("departmentId")), 0)
                .then((res) => {
                    let chartData = []
                    chartData.push({
                        name: '总网格长 '+this.state.totalName,
                        value: this.state.totalPhone,
                        children: res.data
                    })
                    this.setState({
                        chartData: chartData,
                        chartLoading: false
                    })
                })
            }
    }



    render() {
        let { sortedInfo, filteredInfo } = this.state;
        sortedInfo = sortedInfo || {};
        filteredInfo = filteredInfo || {};

        const columns = [
            {
                title: "网格编号",
                dataIndex: "id",
                key: "id"
            },
            {
                title: "网格名称",
                dataIndex: "gridname",
                key: "gridname",
            }, {
                title: "网格负责人",
                dataIndex: "gridcharge",
                key: "gridcharge",
            },
            {
                title: "手机号",
                dataIndex: "phone",
                key: "phone"
            },
            {
                title: "网格长等级",
                dataIndex: "gridlevel",
                key: "gridlevel",
            },
            {
                title: "操作详情",
                key: "action",
                render: (text, record) => (
                    <span>
                        <a onClick={() => this.handleClickOpenModal("add", record)}>添加</a>
                        <Divider type="vertical" />
                        <a onClick={() => this.handleClickOpenModal("update", record)}>修改</a>
                        <Divider type="vertical" />

                        <Popconfirm title="确定删除？" onConfirm={() => { this.confirmDelete(record) }} okText="确定" cancelText="取消">
                            <a>删除</a>
                        </Popconfirm>
                    </span>
                ),

            }
        ];
        const columns1  = [
            {
                title: "网格编号",
                dataIndex: "id",
                key: "id"
            },
            {
                title: "网格负责人",
                dataIndex: "gridcharge",
                key: "gridcharge",
            },
            {
                title: "手机号",
                dataIndex: "phone",
                key: "phone"
            },
            {
                title: "网格长等级",
                dataIndex: "gridlevel",
                key: "gridlevel",
            },
            {
                title: "操作详情",
                key: "action",
                render: (text, record) => (
                    <span>
                        {/* <a onClick={() => this.handleClickOpenModal("update", record)}>修改</a>
                        <Divider type="vertical" /> */}

                        <Popconfirm title="确定删除？" onConfirm={() => { this.confirmDeleteTotal(record) }} okText="确定" cancelText="取消">
                            <a>删除</a>
                        </Popconfirm>
                    </span>
                ),

            }
        ];
        
        const { uploading, fileList } = this.state;
        const props = {
            onRemove: file => {
                this.setState(state => {
                    const index = state.fileList.indexOf(file);
                    const newFileList = state.fileList.slice();
                    newFileList.splice(index, 1);
                    return {
                        fileList: newFileList,
                    };
                });
            },
            beforeUpload: file => {

                this.setState(state => ({
                    fileList: [...state.fileList, file],
                }));

                return false;
            },
            fileList,
        }

        return (
            <div>

                <div style={{ marginBottom: 15 }}>
                    <Button type="primary" onClick={() => this.showAddModal(1)} size="large" style={{ marginLeft: 15 }}>
                        <Icon type="user" theme="outlined" />网格信息导入
                    </Button>
                    <Button type="primary" onClick={()=>this.handleClickOpenModal3()} size="large" style={{ marginLeft: 15 }}> 新增网格长信息</Button>
                    <Popconfirm title="确定删除所有网格信息？" onConfirm={() => { this.confirmDelete1() }} okText="确定" cancelText="取消" disabled={this.state.isHasGridInfo}>
                    <Button type="primary" onClick={() => this.handleClickOpenModal2()} size="large" style={{ marginLeft: 15 }} disabled={this.state.isHasGridInfo}>
                        网格信息删除
                    </Button>
                    </Popconfirm>
                    <Button href={gridInAdminUrl} style={{ marginLeft: 15 }} size="large"><Icon type="download" />下载网格长导入模板</Button>
                    <Modal
                        closable={true}
                        centered
                        destroyOnClose={true}
                        visible={this.state.modlVisible}
                        onOk={() => this.child.handlesubmit()}
                        onCancel={() => this.setModalVisible(false)}
                    >
                        <AddInAdminGridForm record={this.state.selectrecord} submitmodal={this.setModalVisible.bind(this)} onRef={(child)=>this.child=child} refresh={this.refreshData} />
                    </Modal>
                    <Modal
                        title={"新增子级网格信息"}
                        closable={true}
                        centered
                        destroyOnClose={true}
                        visible={this.state.modAddlVisible}
                        onOk={() => this.child.handlesubmit()}
                        onCancel={() => this.setModalVisible3(false)}
                    >
                        <AddSubGridRelationInfoForm record={this.state.selectrecord} submitmodal={this.setModalVisible3.bind(this)} onRef={(child)=>this.child=child} refresh={this.refreshData} />
                    </Modal>

                    {/* <Modal
                        title={"新增一级网格信息"}
                        closable={true}
                        centered
                        destroyOnClose={true}
                        visible={this.state.modlVisible2}
                        onOk={() => this.child.handlesubmit()}
                        onCancel={() => this.setModalVisible2(false)}
                    >
                        <AddGridRelationInfoForm submitmodal={this.setModalVisible2.bind(this)} onRef={(child)=>this.child=child} refresh={this.refreshData} />
                    </Modal> */}
                    <Modal
                        title={"新增网格长信息"}
                        closable={true}
                        centered
                        destroyOnClose={true}
                        visible={this.state.modlVisible3}
                        onOk={() => this.child.handlesubmit()}
                        onCancel={() => this.setModalVisible4(false)}
                    >
                        <AddGridAddressAndChargeInfoForm submitmodal={this.setModalVisible4.bind(this)} onRef={(child)=>this.child=child} refresh={this.refreshData} />
                    </Modal>



                    {
                        this.state.addVisible ? (
                            <Modal
                                title={"导入网格长信息"}
                                visible={this.state.addVisible}
                                onCancel={this.handleCancel}
                                closable
                                footer={[]}
                                centered={true}
                                style={{ marginLeft: 15 }}
                            >
                                <Spin tip="导入数据时间较长，请耐心等待！" spinning={this.state.uploading} size="large">
                                    <Upload {...props}>
                                        <Button >
                                            <Icon type="upload" />选择文件
                                        </Button>
                                    </Upload>

                                    <Button
                                        type="primary"
                                        onClick={this.handleUpload}
                                        disabled={fileList.length === 0}
                                        loading={uploading}
                                        style={{ marginTop: 16 }}
                                    >
                                        {uploading ? '正在上传' : '开始上传'}
                                    </Button>
                                </Spin>
                            </Modal>) : null
                    }
                </div>
                <Tabs defaultActiveKey="1" onChange={this.callback}>
               
                    <TabPane tab="表格" key="1">
                        <Table
                            dataSource={this.state.gridInfo}
                            columns={columns}
                            bordered={true}
                            loading={this.state.tableLoading}
                            locale={{ emptyText: '暂无数据' }}
                            onChange={this.handleChange}
                            expandedRowRender={(record) => {
                                return (
                                    <GridInnerTable
                                        onRef={this.onRef}
                                        gridId={record.id}
                                        that={this} />)
                            }}
                        />
                        
                    </TabPane>
                    <TabPane tab="图表" key="2">
                        <div style={{
                            marginBottom: 16,
                            padding: 20,
                            width: '100%',
                            height: 800,
                            border: '1px solid',
                            borderColor: '#f5f5f5'
                        }}>
                            <Skeleton loading={this.state.chartLoading} active>
                                <ChartGridInfo
                                    that={this}
                                    chartData={this.state.chartData}
                                />
                            </Skeleton>
                        </div>
                    </TabPane>
                    <TabPane tab="总网格长信息" key="3">
                        <Table
                            dataSource={this.state.totalInfo}
                            columns={columns1}
                            bordered={true}
                            loading={this.state.tableLoading}
                            locale={{ emptyText: '暂无数据' }}
                            onChange={this.handleChange}
                        />
                    </TabPane>
                </Tabs>

            </div>
        )
    }
}

//树形结构额外扩展
class GridInnerTable extends Component {
    constructor(props) {
        super(props);
        this.state = {
            alertVisible: false, //提示
            confirmLoading: false,
            msg: "", //提交失败时的提示语
            // searchText: '',
            tableLoading: true,
            gridId: props.gridId,
            gridInfo: [],
            
            that: props.that,
            selectrecord: {},
            modAddlVisible: false
        };
    }

    componentDidMount() {
        this.refreshData();
        this.props.onRef(this);
    }

    componentWillReceiveProps(props) {
        // console.log('props', props)
        this.setState({
            gridId: props.gridId,
            that: props.that,
        });
        this.refreshData();
    }
    onRef = (ref) => {
        this.child = ref
    }

    refreshData() {
        getAllGridByGridparentIdApi(parseInt(sessionStorage.getItem("departmentId")), this.state.gridId)
            .then((res) => {
                this.setState({
                    gridInfo: res.data,
                    tableLoading: false
                })
            })
            

    }
    refreshData2 = () => {
        this.setState({
            tableLoading: true
        })
        getAllGridByGridparentIdApi(parseInt(sessionStorage.getItem("departmentId")), sessionStorage.getItem("gridparentId"))
            .then((res) => {
                this.setState({
                    gridInfo: res.data,
                    tableLoading: false
                })
            })
    }


    handleClickOpenModal = (type, record) => {
       // console.log(record)
        if (type == 'update') {
            //console.log("update")
            this.setState({
                modlVisible: true,
                selectrecord: record,
            })
        } else if (type == 'add') {
           // console.log("add")
            this.setState({
                modAddlVisible: true,
                selectrecord: record,
            })
        }
    }

    confirmDelete = (record) => {
        const schoolId = parseInt(sessionStorage.getItem("departmentId"))
        deleteGridInfoApi(record.id || record.key, schoolId)
            .then(res => {
                if (res.data == 'success') {
                    this.refreshData()
                    success()
                }
                else {
                    fail('删除失败')
                }

            })
    }
    setModalVisible(modlVisible) {
        this.setState({
            modlVisible: modlVisible,
            selectrecord: {}
        })
    }
    setModalVisible2(modlVisible) {
        this.setState({
            modAddlVisible: modlVisible,
            selectrecord: {}
        })
    }


    render() {
        const innerColumns = [
            {
                title: "网格编号",
                dataIndex: "id",
                key: "id"
            },
            {
                title: "网格名称",
                dataIndex: "gridname",
                key: "gridname",
            }, {
                title: "网格负责人",
                dataIndex: "gridcharge",
                key: "gridcharge",
            },
            {
                title: "手机号",
                dataIndex: "phone",
                key: "phone"
            },
            {
                title: "网格长等级",
                dataIndex: "gridlevel",
                key: "gridlevel",
            },
            {
                title: "操作详情",
                key: "action",
                render: (text, record) => (
                    <span>
                        <a onClick={() => this.handleClickOpenModal("add", record)}>添加</a>
                        <Divider type="vertical" />
                        <a onClick={() => this.handleClickOpenModal("update", record)}>修改</a>
                        <Divider type="vertical" />

                        <Popconfirm title="确定删除？" onConfirm={() => { this.confirmDelete(record) }} okText="确定" cancelText="取消">
                            <a>删除</a>
                        </Popconfirm>
                    </span>
                ),

            }
        ];

        return (
            <div>
                <Table
                    columns={innerColumns}
                    dataSource={this.state.gridInfo}
                    pagination={false}
                    loading={this.state.tableLoading}
                    locale={{ emptyText: '暂无数据' }}
                    bordered={true}
                    expandedRowRender={(record) => {
                        return (
                            <GridInnerTable
                                onRef={this.onRef}
                                gridId={record.id}
                                that={this} />)
                    }}
                />
                <Modal
                    title={"新增子级网格信息"}
                    closable={true}
                    centered
                    destroyOnClose={true}
                    visible={this.state.modAddlVisible}
                    onOk={() => this.child.handlesubmit()}
                    onCancel={() => this.setModalVisible2(false)}
                >
                    <AddSubGridRelationInfoForm record={this.state.selectrecord} submitmodal={this.setModalVisible2.bind(this)} onRef={(child)=>this.child = child} refresh={this.refreshData2} />
                </Modal>
                <Modal
                    closable={false}
                    centered
                    destroyOnClose={true}
                    visible={this.state.modlVisible}
                    onOk={() => this.child.handlesubmit()}
                    onCancel={() => this.setModalVisible(false)}
                >
                    <AddInAdminGridForm record={this.state.selectrecord} submitmodal={this.setModalVisible.bind(this)} onRef={(child)=>this.child = child} refresh={this.refreshData2} />
                </Modal>
            </div>

        )
    }
}

//========================================================修改网格信息================================
class addinadmingridform extends Component {
    constructor(props) {
        super(props);
        this.state = {
            id: this.props.record.id ? this.props.record.id : null,
            record: this.props.record,
        }

    }

    componentDidMount() {
        this.props.onRef(this);

    }
    componentWillReceiveProps(props) {
        if (JSON.stringify(props.record) != JSON.stringify(this.state.record)) {
            this.setState({
                record: props.record,
            })
        }
    }

    handleChange = (selectedKeys, selectedItems) => {
        this.setState({
            id: parseInt(selectedItems.key),
            type: selectedKeys
        })

    }

    handlesubmit = e => {
        let gridlist = []
        gridlist = this.props.form.getFieldsValue();
        sessionStorage.setItem("gridparentId", this.state.record.gridparentId);
        let a = "schoolId";
        let b = 'id'
        gridlist[a] = parseInt(sessionStorage.getItem("departmentId"))
        gridlist[b] = this.state.record.id || this.state.record.key

        if (gridlist.gridname || gridlist.gridcharge || gridlist.phone) {

            updateGridInfoApi(gridlist, this.state.record.gridchargeId, this.state.record.gridnameId)
                .then(res => {
                    if (res.data == 'success') {
                        this.props.submitmodal(false)
                        this.props.refresh()
                        this.props.form.resetFields()
                        success()
                    }
                    else {
                        fail('操作失败')
                    }
                })
        }
        else {
            fail('操作失败，请至少填写一项特殊类型')

        }


    }


    render() {
        const { getFieldDecorator, getFieldValue } = this.props.form;
        const formItemLayout = {
            labelCol: { span: 5 },
            wrapperCol: { span: 14 },
        };

        return (
            <div style={{ marginBottom: 16, marginTop: 32 }}>
                <Form onSubmit={this.handlesubmit}>
                    <FormItem
                        label='网格名称'
                        {...formItemLayout}>
                        {getFieldDecorator("gridname", { initialValue: this.state.record.gridname ? this.state.record.gridname : null }, {

                            rules: [{
                                required: true,
                            }]
                        })(<Input
                            style={{ width: '100%' }}
                            placeholder="请填写内容"
                        ></Input>
                        )}
                    </FormItem>


                    <FormItem
                        label='网格人员'
                        {...formItemLayout}>
                        {getFieldDecorator("gridcharge", { initialValue: this.state.record.gridcharge ? this.state.record.gridcharge : null }, {

                            rules: [{
                                required: true,
                            }]
                        })(<Input
                            style={{ width: '100%' }}
                            placeholder="请填写内容"
                        ></Input>)}
                    </FormItem>
                    <FormItem
                        label='手机号'
                        {...formItemLayout}>
                        {getFieldDecorator("phone", { initialValue: this.state.record.phone ? this.state.record.phone : null }, {

                            rules: [{
                                required: true,

                            }]
                        })(<Input
                            style={{ width: '100%' }}
                            placeholder="请填写内容"
                        ></Input>)}
                    </FormItem>

                </Form>
            </div>
        );
    }
}
const AddInAdminGridForm = Form.create()(addinadmingridform);

//========================================================新增一级网格信息================================
class addGridRelationInfoForm extends Component {
    constructor(props) {
        super(props);
        this.state = {
            firstGridAddressInfo: [],
            firstGridChargeInfo: []
        }

    }

    componentDidMount() {
        this.props.onRef(this);
        this.refreshData()
    }

    componentWillReceiveProps(props) {

    }
    refreshData() {
        getFirstGridAddressInfoApi(parseInt(sessionStorage.getItem("departmentId")), 1)
            .then((res) => {
                this.setState({
                    firstGridAddressInfo: res.data,
                })
            })
        getFirstGridChargeInfoApi(parseInt(sessionStorage.getItem("departmentId")), 1)
            .then((res) => {
                this.setState({
                    firstGridChargeInfo: res.data,
                })
            })
    }

    handlesubmit = e => {
        this.props.form.validateFields((err, values) => {
            if (!err) {
                addFirstGridInfoApi(parseInt(sessionStorage.getItem("departmentId")), values.gridnameId, values.gridchargeId, 0)
                    .then(res => {
                        if (res.data == 'success') {
                            this.props.submitmodal(false)
                            this.props.refresh()
                            this.props.form.resetFields()
                            success("添加成功!")
                        }
                        else if (res.data == 'fail2') {
                            fail('不要重复添加!')
                        } else {
                            fail('操作失败!')
                        }
                    })
            }
        })
    }


    render() {
        const { getFieldDecorator, getFieldValue } = this.props.form;
        const formItemLayout = {
            labelCol: { span: 5 },
            wrapperCol: { span: 14 },
        };

        const gridaddressoption = this.state.firstGridAddressInfo.map((d, index) => <Option value={d.id} key={index}>{d.gridname}</Option>);
        const gridchargeoption = this.state.firstGridChargeInfo.map(v1 => {
            return (
                <Option key={v1.id} title={v1.gridcharge} value={v1.id}>{v1.gridcharge}</Option>
            );
        });

        return (
            <div style={{ marginBottom: 16, marginTop: 32 }}>
                <Form onSubmit={this.handlesubmit}>
                    <FormItem
                        label='网格名称'
                        {...formItemLayout}>
                        {getFieldDecorator("gridnameId", {
                            rules: [{
                                required: true,
                                message: "网格名称不能为空!"
                            }]
                        })(<Select
                            allowClear
                            size="large"
                            placeholder="选择网格名称">
                            {gridaddressoption}
                        </Select>
                        )
                        }
                    </FormItem>
                    <FormItem
                        label='网格负责人'
                        {...formItemLayout}>
                        {getFieldDecorator("gridchargeId", {

                            rules: [{
                                required: true,
                                message: "网格负责人不能为空!"
                            }]
                        })(<Select
                            allowClear
                            size="large"
                            placeholder="选择网格负责人"
                            showSearch
                            optionFilterProp="children"
                            // filterOption={(input, option) =>{
                            //     console.log(input, option)
                            //     return option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                            //    }}
                             >{gridchargeoption}

                        </Select>
                        )}
                    </FormItem>
                </Form>
            </div>
        );
    }
}
const AddGridRelationInfoForm = Form.create()(addGridRelationInfoForm);

//========================================================新增网格长信息==================================
 class addGridChargeInfoForm extends Component {
     constructor(props){
         super(props);
         this.state={
             gridLevelInfo:[],
             level:[]
         }
     }
     componentDidMount(){
        this.props.onRef(this);
        this.refreshData()
        console.log("zzss"+this.state.gridLevelInfo)
     }
     refreshData(){
         getAllGridChargeLevelApi(parseInt(sessionStorage.getItem("departmentId")))
         .then((res)=>{
            // console.log("as")
            // console.log(res.data)
             let gridLevel=[]
             
             for(let i=0; i<res.data.length;i++){
                let Lname="";
                switch(res.data[i]){
                    case 1:
                        Lname="一级网格长"
                        break;
                    case 2:                          
                        Lname='二级网格长'                         
                       break;  
                   case 3:                           
                        Lname='三级网格长'                         
                       break;
                   case 4:                       
                    Lname='四级网格长'                    
                        break;                         
                    case 5:      
                        Lname='五级网格长'      
                       break;     
                }
                gridLevel.push({
                    id:res.data[i],
                    name:Lname
                })
                
            }
            gridLevel.push({
                id:0,
                name:'总网格长'
            })
            this.setState({
                gridLevelInfo:gridLevel
            })
            
         })
     }
     handlesubmit = e => {
        this.props.form.validateFields((err, values) => {
            if (!err) {
                addGridAddressAndChargeInfo(parseInt(sessionStorage.getItem("departmentId")), values.gridname, values.gridlevel, values.gridcharge, values.phone)
                    .then(res => {
                        if (res.data == 'success') {
                            this.props.submitmodal(false)
                            this.props.refresh()
                            this.props.form.resetFields()
                            success("添加成功!")
                        }
                        else if (res.data == 'fail2') {
                            fail('不要重复添加!')
                        } else {
                            fail('操作失败!')
                        }
                    })
            }
        })
    }
    render(){
        const { getFieldDecorator, getFieldValue } = this.props.form;
        const formItemLayout = {
            labelCol: { span: 5 },
            wrapperCol: { span: 14 },
        };
        const gridleveloption = this.state.gridLevelInfo.map((d, index) => <Option value={d.id} key={index}>{d.name}</Option>); 
        return (
            <div style={{ marginBottom: 16, marginTop: 32 }}>
                <Form onSubmit={this.handlesubmit}>
                    <FormItem
                        label='网格名称'
                        {...formItemLayout}>
                        {getFieldDecorator("gridname", {
                            rules: [{
                                required: true,
                                message: "网格名称不能为空!"
                            }]
                        })(
                            <Input
                                size="large"
                               
                                type="text"
                                placeholder="请输入网格名称"
                                
                            />
                        )}
                    </FormItem>
                    <FormItem
                        label='网格负责人'
                        {...formItemLayout}>
                        {getFieldDecorator("gridcharge", {

                            rules: [{
                                required: true,
                                message: "网格负责人不能为空!"
                            }]
                        })(
                            <Input
                                size="large"
                                allowClear
                                type="text"
                                placeholder="请输入网格负责人"
                                
                            />
                        )}
                    </FormItem>
                    <FormItem
                        label='负责人电话'
                        {...formItemLayout}>
                        {getFieldDecorator("phone", {

                            rules: [{
                                required: true,
                                pattern: /^1[3|4|5|7|8][0-9]\d{8}$/,
                                 message: '请输入正确的手机号'
                            }]
                        })(
                            <Input
                                size="large"
                                allowClear
                                type="text"
                                placeholder="请输入网格负责人电话"
                                
                            />
                        )}
                    </FormItem>
                    <FormItem
                        label='网格长等级'
                        {...formItemLayout}>
                        {getFieldDecorator("gridlevel", {
                            rules: [{
                                required: true,
                                message: "网格长等级不能为空"
                            }]
                        })(<Select
                            allowClear
                            size="large"
                            placeholder="选择网格长等级">
                            {gridleveloption}
                        </Select>
                        )
                        }
                    </FormItem>
                </Form>
            </div>
        ); 
    }
 }
 const AddGridAddressAndChargeInfoForm=Form.create()(addGridChargeInfoForm);
//========================================================新增子级网格信息================================
class addSubGridRelationInfoForm extends Component {
    constructor(props) {
        super(props);
        this.state = {
            record: this.props.record,
            subGridAddressInfo: [],
            subGridChargeInfo: [],
        }

    }
    componentDidMount() {
        this.props.onRef(this);
        this.refreshData()
        
    }

    componentWillReceiveProps(props) {
        if (JSON.stringify(props.record) != JSON.stringify(this.state.record)) {
            this.setState({
                record: props.record,
            }, () => {
                this.refreshData();
            })
        }
    }
    refreshData() {
        getFirstGridAddressInfoApi(parseInt(sessionStorage.getItem("departmentId")), this.state.record.gridlevel + 1)
            .then((res) => {
                this.setState({
                    subGridAddressInfo: res.data,
                })
            })
        getFirstGridChargeInfoApi(parseInt(sessionStorage.getItem("departmentId")), this.state.record.gridlevel + 1)
            .then((res) => {
                this.setState({
                    subGridChargeInfo: res.data,
                })
            })
    }

    handlesubmit = (e) => {
        sessionStorage.setItem("gridparentId", this.state.record.gridparentId);
        this.props.form.validateFields((err, values) => {
            if (!err) {
                addFirstGridInfoApi(parseInt(sessionStorage.getItem("departmentId")), values.gridnameId, values.gridchargeId, this.state.record.id)
                    .then(res => {
                        if (res.data == 'success') {
                            this.props.submitmodal(false)
                            this.props.refresh()
                            this.props.form.resetFields()
                            success("添加成功!")
                        }
                        else if (res.data == 'fail2') {
                            fail('不要重复添加!')
                        } else {
                            fail('操作失败!')
                        }
                    })
            } else {
               // console.log("error")
            }
        })
    }


    render() {
        const { getFieldDecorator, getFieldValue } = this.props.form;
        const formItemLayout = {
            labelCol: { span: 5 },
            wrapperCol: { span: 14 },
        };
        let gridaddressoption
        let gridchargeoption
        if(this.state.subGridAddressInfo.length != 0 && this.state.subGridChargeInfo.length !=0){
            gridaddressoption = this.state.subGridAddressInfo.map((d, index) => <Option value={d.id} key={index}>{d.gridname}</Option>);
            gridchargeoption = this.state.subGridChargeInfo.map((d, index) => <Option value={d.id} key={index}>{d.gridcharge}</Option>);
        }

        return (
            <div style={{ marginBottom: 16, marginTop: 32 }}>
                <Form onSubmit={this.handlesubmit.bind()}>
                    <FormItem
                        label='网格名称'
                        {...formItemLayout}>
                        {getFieldDecorator("gridnameId", {
                            rules: [{
                                required: true,
                                message: "网格名称不能为空!"
                            }]
                        })(<Select
                            allowClear
                            size="large"
                            placeholder="选择网格名称">
                            {gridaddressoption}
                        </Select>
                        )}
                    </FormItem>
                    <FormItem
                        label='网格负责人'
                        {...formItemLayout}>
                        {getFieldDecorator("gridchargeId", {

                            rules: [{
                                required: true,
                                message: "网格负责人不能为空!"
                            }]
                        })(<Select
                            allowClear
                            size="large"
                            placeholder="选择网格负责人">
                            {gridchargeoption}
                        </Select>
                        )}
                    </FormItem>
                    {/* <FormItem>
                        <Button type="primary" htmlType="submit">确定</Button>
                    </FormItem> */}
                </Form>
            </div>
        );
    }
}
const AddSubGridRelationInfoForm = Form.create()(addSubGridRelationInfoForm);

//========================================================树状图================================
class ChartGridInfo extends Component {
    constructor(props) {
        super(props);
        this.state = {
            chartData: props.chartData,
            that: props.that
        };
    }

    componentWillReceiveProps(props) {
        if (JSON.stringify(props.chartData) != JSON.stringify(this.state.chartData)) {
            this.setState({
                chartData: props.chartData,
                that: props.that
            }, () => {
                setTimeout(()=>{this.drawChart()}, 500)
            })
        }
    }

    componentDidMount() {
        setTimeout(()=>{this.drawChart()}, 500)
    }

    drawChart() {
        if (JSON.stringify(this.state.chartData) != '[]') {
            // console.log(this.state.chartData);
            let chart = echarts.init(document.getElementById('chartSearch'));
            chart.setOption({
                //垂直树状图
                // tooltip: {
                //     trigger: 'item',
                //     triggerOn: 'mousemove'
                //   },
                //   series: [
                //     {
                //       type: 'tree',
                //       data: this.state.chartData,
                //       left: '2%',
                //       right: '2%',
                //       top: '8%',
                //       bottom: '20%',
                //       symbol: 'emptyCircle',
                //       orient: 'vertical',
                //       expandAndCollapse: true,
                //       label: {
                //         position: 'top',
                //         rotate: -90,
                //         verticalAlign: 'middle',
                //         align: 'right',
                //         fontSize: 9
                //       },
                //       leaves: {
                //         label: {
                //           position: 'bottom',
                //           rotate: -90,
                //           verticalAlign: 'middle',
                //           align: 'left'
                //         }
                //       },
                //       animationDurationUpdate: 750
                //     }
                //   ]
                title: {
                    text: '校内网格信息展示',
                    left: 'center',
                },
                tooltip: {
                    trigger: 'item',
                    triggerOn: 'mousemove'
                },
                series: [
                    {
                        type: 'tree',
                        data: this.state.chartData,
                        top: '5%',
                        left: '15%',
                        // orient: 'vertical',
                        bottom: '1%',
                        right: '20%',
                        symbolSize: 9,
                        label: {
                            position: 'left',
                            // rotate: -90,
                            verticalAlign: 'middle',
                            align: 'right',
                            fontSize: 15
                        },
                        leaves: {
                            label: {
                                position: 'right',
                                // rotate: -90,
                                verticalAlign: 'middle',
                                align: 'left'
                            }
                        },
                        emphasis: {
                            focus: 'descendant'
                        },
                        expandAndCollapse: true,
                        animationDuration: 550,
                        animationDurationUpdate: 750
                    }
                ]
            })
            window.addEventListener('resize', () => {
                window.onresize = chart.resize;
            })
        }

    }

    render() {
        let chartStyle = {
            height: '100%',
            width: '100%',
        };
        return (<div id='chartSearch' style={chartStyle} />)
    }
}

//===================================================================================测试树形结构======================================================================
class TreeDemo extends Component {

    constructor(props) {
        super(props);
        this.state = {
            gridMember: []
        }
    }

    componentDidMount() {

        let gridParent = "0"


        getAllInAdminGridMemberByGridparentApi(parseInt(sessionStorage.getItem("departmentId")), gridParent)
            .then((res) => {

                let gridMemberOne = []
                res.data.forEach((item, index) => {
                    gridMemberOne.push({
                        //key: item.id,
                        id: item.key,
                        type: item.type,
                        gridName: item.gridName,
                        gridNumber: item.gridNumber,
                        gridAdmin: item.gridAdmin,
                        adminPhone: item.adminPhone,
                        // children: item.children
                    });
                });
                this.setState({
                    gridMember: gridMemberOne
                })

            }).catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                   // console.info(e.response.data)
                   // console.info(e.response.status)
                   // console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                   // console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                   // console.info('error', e.message)
                }
               // console.info(e.config)
            });

    }


    handleClickOpenModal() {

    }

    confirmDelete() {

    }



    render() {

        const columns = [

            {
                title: '网格名称',
                dataIndex: 'gridName',
                key: 'gridName',
            },
            {
                title: '网格编号',
                dataIndex: 'gridNumber',
                key: 'gridNumber',
            },
            {
                title: '网格员姓名',
                dataIndex: 'gridAdmin',
                key: 'gridAdmin',
            },
            {
                title: '手机号',
                dataIndex: 'adminPhone',
                key: 'adminPhone',
            },
            {
                title: '网格级别',
                dataIndex: 'type',
                key: 'id',
            },
            {
                title: "操作详情",
                key: "action",
                render: (text, record) => (
                    <span>
                        <a onClick={() => this.handleClickOpenModal("update", record)}>修改</a>
                        <Divider type="vertical" />

                        <Popconfirm title="确定删除？" onConfirm={() => { this.confirmDelete(record) }} okText="确定" cancelText="取消">
                            <a>删除</a>
                        </Popconfirm>
                    </span>
                ),

            }


        ];



        //   // rowSelection objects indicates the need for row selection
        const rowSelection = {
            onChange: (selectedRowKeys, selectedRows) => {

            },
            onSelect: (record, selected, selectedRows) => {

            },
            onSelectAll: (selected, selectedRows, changeRows) => {
            },
        };

        return (
            <div>
                <Table columns={columns} rowSelection={rowSelection} dataSource={this.state.gridMember} />
            </div>
        )
    }

}






export { ImportGridOneData, TreeDemo }